package com.zyx.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author 22394
 */
@Configuration
@PropertySource("classpath:db.properties")
//扫描有Mapper注解的接口 @Mapper 主要是解决，单元测试时报红
@ComponentScan("com.zyx.mapper")
//也是扫描包，在接口上可以不加@Mapper
@MapperScan("com.zyx.mapper")
@tk.mybatis.spring.annotation.MapperScan(value = "com.zyx.mapper",properties = {"mappers=tk.mybatis.mapper.common.Mapper","notEmpty=true"})
public class MybatisConfig {
    @Value("${db.driver:com.mysql.cj.jdbc.Driver}")
    private String driver;
    @Value("${db.url:jdbc:mysql://localhost:3306/oadb}")
    private String url;
    @Value("${db.username:root}")
    private String username;
    @Value("${db.password}")
    private String password;

    @Bean(name = "ds",initMethod = "init",destroyMethod = "close")
    @Primary
    public DruidDataSource ds() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean(name = "sf")
    @Primary
    public SqlSessionFactoryBean sf(DruidDataSource ds) throws IOException {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);

        // resources/mapper/XxxMapper.xml
        sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml"));

        //扫描定义别名 com.zyx.entity.Student 别名为 student
        sf.setTypeHandlersPackage("com.zyx.entity");
        return sf;
    }
}
